package com.mdd.maduoduo.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mdd.maduoduo.R;
import com.mdd.maduoduo.activity.AddMsgActivity;
import com.mdd.maduoduo.activity.AlreadyReceiveActivity;
import com.mdd.maduoduo.adapter.MainListAdapter;
import com.mdd.maduoduo.di.component.DaggerUIComponent;
import com.mdd.maduoduo.di.component.UIComponent;
import com.mdd.maduoduo.entity.BannerEntity;
import com.mdd.maduoduo.entity.QueryListEntity;
import com.mdd.maduoduo.entity.Response;
import com.mdd.maduoduo.entity.StationEntity;
import com.mdd.maduoduo.entity.UserEntity;
import com.mdd.maduoduo.presenter.LoginPresenter;
import com.mdd.maduoduo.utils.AlertUtils;
import com.mdd.maduoduo.utils.CommonAdapter;
import com.mdd.maduoduo.utils.DpUtils;
import com.mdd.maduoduo.utils.GlideUtils;
import com.mdd.maduoduo.utils.ToastUtils;
import com.mdd.maduoduo.utils.Utils;
import com.mdd.maduoduo.view.interfaces.DeleteCodeView;
import com.mdd.maduoduo.view.interfaces.GetBannerView;
import com.mdd.maduoduo.view.interfaces.GetStationView;
import com.mdd.maduoduo.view.interfaces.QueryListView;
import com.mdd.maduoduo.view.interfaces.UpdateCodeStatusView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class HomeFragment extends BaseFragment implements GetStationView, QueryListView, MainListAdapter.UpdateStatusListener, UpdateCodeStatusView, DeleteCodeView, GetBannerView {

    @Inject
    LoginPresenter mPresenter;
    private ImageView ivAdd;

    private SmartRefreshLayout refreshLayout;

    private LinearLayout llView;

    private int selectPos = 0;

    private StationEntity mStationEntity;

    private int page= 1;

    private MainListAdapter mAdapter;

    private RecyclerView recyclerView;

    private ImageView ivAll;

    private TextView tvAlready;

    private Banner banner;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_home;
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        selectPos = 0;
        mPresenter.getStation(getActivity(),0);
    }

    @Override
    protected void initializeInjector() {
        super.initializeInjector();
        mPresenter = new LoginPresenter();
        UIComponent uiComponent = DaggerUIComponent.builder().applicationComponent(getApplicationComponent())
                .activityModule(getActivityModule()).build();
        uiComponent.inject(this);
        mPresenter.setGetStationView(this);
        mPresenter.setQueryListView(this);
        mPresenter.setUpdateCodeStatusView(this);
        mPresenter.setDeleteCodeView(this);
        mPresenter.setGetBannerView(this);
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        ivAdd = view.findViewById(R.id.ivAdd);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        llView = view.findViewById(R.id.llView);
        ivAll = view.findViewById(R.id.ivAll);
        tvAlready = view.findViewById(R.id.tvAlready);
        recyclerView = view.findViewById(R.id.recyclerView);
        banner = view.findViewById(R.id.banner);
        mAdapter = new MainListAdapter();
        recyclerView.setAdapter(mAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter.setListener(this);
        mAdapter.setOnItemLongClickListener(new CommonAdapter.OnItemLongClickListener<QueryListEntity.DataDTO.RecordsDTO>() {
            @Override
            public boolean onItemLongClick(CommonAdapter<QueryListEntity.DataDTO.RecordsDTO> adapter, View view, int position, QueryListEntity.DataDTO.RecordsDTO item) {
                AlertUtils.normalBtnAlert(getActivity(), "温馨提示","确定要删除该取件码吗？","取消","确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mPresenter.deleteCode(item.id,0);
                        AlertUtils.dismiss();
                    }
                });
                return false;
            }
        });

        ivAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = "确定要将【" + mStationEntity.data.records.get(selectPos).stationName +"】(共"+mStationEntity.data.records.get(selectPos).statusNumber+"个)标记为已取件吗？";
                AlertUtils.normalBtnAlert(getActivity(), "温馨提示",content,"取消","确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mPresenter.updateCodeStatus(getActivity(),"",1,1,mStationEntity.data.records.get(selectPos).stationName);
                        AlertUtils.dismiss();
                    }
                });
            }
        });


        mPresenter.getBannerList("2001");
    }

    @Override
    protected void onClick() {
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), AddMsgActivity.class));
            }
        });

        tvAlready.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), AlreadyReceiveActivity.class));
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void renderSuccess(StationEntity stationEntity) {
        mStationEntity = stationEntity;
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout rs) {
                if (!mStationEntity.data.records.isEmpty()){
                    page = 1;
                    mPresenter.queryList(getActivity(),page,10,0,mStationEntity.data.records.get(selectPos).stationName,0);
                }
                refreshLayout.finishRefresh(2000);
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout rs) {
                if (!mStationEntity.data.records.isEmpty()){
                    page ++;
                    mPresenter.queryList(getActivity(),page,10,0,mStationEntity.data.records.get(selectPos).stationName,0);
                }
                refreshLayout.finishLoadMore(2000);
            }
        });
        if (mStationEntity.data.records!=null){
            if (!mStationEntity.data.records.isEmpty()){
                ivAll.setVisibility(View.VISIBLE);//如果驿站数据为空 则全选按钮不展示
                refreshUi(mStationEntity);
            }else{
                ivAll.setVisibility(View.GONE);//如果驿站数据为空 则全选按钮不展示
                refreshUi(mStationEntity);
            }
        }else{
            ivAll.setVisibility(View.GONE);//如果驿站数据为空 则全选按钮不展示
        }
    }

    @SuppressLint("SetTextI18n")
    private void refreshUi(StationEntity stationEntity) {
        llView.removeAllViews();
        for (int i = 0; i < stationEntity.data.records.size(); i++) {
            TextView textView = new TextView(getActivity());
            textView.setText(stationEntity.data.records.get(i).stationName+" "+stationEntity.data.records.get(i).statusNumber);
            if (selectPos==i){
                textView.setBackgroundResource(R.drawable.shape_radius_200_color_000000);
                textView.setTextColor(Color.parseColor("#FFFFFF"));
            }else {
                textView.setBackgroundResource(R.drawable.shape_radius_200_color_ffffff);
                textView.setTextColor(Color.parseColor("#000000"));
            }

            textView.setPadding(DpUtils.dip2px(getActivity(),12),DpUtils.dip2px(getActivity(),5),DpUtils.dip2px(getActivity(),12),DpUtils.dip2px(getActivity(),5));
            int finalI = i;
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    selectPos = finalI;
                    refreshUi(mStationEntity);
                    page = 1;
                    refreshLayout.autoRefresh();
                }
            });
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(10, 0, 10, 0);
            llView.addView(textView, params);
        }

        if(mStationEntity.data.records.size()>0){
            mPresenter.queryList(getActivity(),page,10,0,mStationEntity.data.records.get(selectPos).stationName,0);
        }else{
            mAdapter.setData(new ArrayList<>());
        }
//        refreshLayout.autoRefresh();
    }

    @Override
    public void renderSuccess(QueryListEntity queryListEntity) {
        if (page==1){
            mAdapter.setData(queryListEntity.data.records);
        }else {
            mAdapter.addData(queryListEntity.data.records);
        }
        if (queryListEntity.data.pages == page){
            refreshLayout.finishLoadMoreWithNoMoreData();
        }else {
            refreshLayout.setNoMoreData(false);  // 逆转无更多数据状态
        }
    }

    @Override
    public void update(QueryListEntity.DataDTO.RecordsDTO data) {
        mPresenter.updateCodeStatus(getActivity(),data.id,1,0,"");
    }

    @Override
    public void renderSuccess(Response response) {
        if (response.code.equals("200")){
            ToastUtils.showLongToast(getActivity(),"取件成功");
            page = 1;
            selectPos = 0;
            mPresenter.getStation(getActivity(),0);
        }else {
            ToastUtils.showLongToast(getActivity(),response.msg);
        }
    }

    @Override
    public void renderDeleteSuccess(Response response) {
        if (response.code.equals("200")){
            ToastUtils.showLongToast(getActivity(),"删除成功");
            page = 1;
            selectPos = 0;
            mPresenter.getStation(getActivity(),0);
        }
    }

    @Override
    public void renderBannerSuccess(BannerEntity bannerEntity) {
        List<BannerEntity.DataDTO.FunctionConfigDtosDTO> listBanner = bannerEntity.data.functionConfigDtos;
        if (!listBanner.get(0).itemDtos.isEmpty()){
            banner.setVisibility(View.VISIBLE);
            //加载banner数据
            banner.setAdapter(new BannerImageAdapter<BannerEntity.DataDTO.FunctionConfigDtosDTO.ItemDtosDTO>(listBanner.get(0).itemDtos) {
                @Override
                public void onBindView(BannerImageHolder holder, BannerEntity.DataDTO.FunctionConfigDtosDTO.ItemDtosDTO data, int position, int size) {
                    GlideUtils.getInstances().loadNormalImg(getActivity(),holder.imageView,data.url);
                }
            });
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(Object data, int position) {
                    //根据jumpType判断跳转位置 点击跳转类型:0-跳转网页、1-跳转五星好评、2-执行分享功能、3-跳转打赏界面、4-跳转Max会员购买界面、6-跳转小程序、7-客服电话(有拨打效果)、8-仅展示(点击可复制)、9-跳转多人共享界面
                    BannerEntity.DataDTO.FunctionConfigDtosDTO.ItemDtosDTO bean = (BannerEntity.DataDTO.FunctionConfigDtosDTO.ItemDtosDTO) data;
                    Utils.jumpOther(getActivity(),bean);
                }
            });
            // 设置指示器
            banner.setIndicator(new CircleIndicator(this.getContext()));
            // 设置指示器位置
            banner.setIndicatorGravity(IndicatorConfig.Direction.CENTER);
            banner.start();
        }else {
            banner.setVisibility(View.GONE);
        }
    }
}
